#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <cstdio>
#include <cstring>

void *thread_run(void *arg)
{

    std::string str = static_cast<const char *>(arg);
    delete[] static_cast<char *>(arg); // 释放传入的内存
    int i = 5;
    while (i--)
    {
        std::cout << "I am a thread , my name is " << str << std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    const int num = 10;
    std::vector<pthread_t> tids;
    for (int i = 0; i < num; ++i)
    {
        pthread_t tid;
        // char id[64]; 每次循环都会覆盖
        char *id = new char[64]; // 每次循环都分配一块新的内存
        snprintf(id, 64, "thread-%d", i);
        int n = pthread_create(&tid, nullptr, thread_run, id);
        if (n == 0)
            tids.push_back(tid);
        sleep(2);
    }

    for (auto &tid : tids)
    { //  一个一个的等待
        int n = pthread_join(tid, nullptr);
        if (n == 0)
            std::cout << "thread " << tid << " has finished" << "等待新线程成功" << std::endl;
    }
    while (true)
    {
        std::cout << "I am main thread" << std::endl;
        sleep(1);
    }

    return 0;
}
